package com.example.springsecuritydemo.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Classname: MyAuthenticationSuccessHandler
 * @Description: AuthenticationSuccessHandler自定义登录成功处理器
 * @Date: 2021/3/15 22:12
 * @Created: by Wang Xu
 */
@Slf4j
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final String url;

    public MyAuthenticationSuccessHandler(String url) {
        this.url = url;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        log.info(request.getRemoteAddr());
        log.info(request.getRemoteUser());
        log.info(request.getRemoteHost());
        int remotePort = request.getRemotePort();
        log.info(String.valueOf(remotePort));

        User user = (User) authentication.getPrincipal();
        System.out.println(user.getUsername());
        // 考虑到安全，不能拿到密码，会输出null
        System.out.println(user.getPassword());
        System.out.println(user.getAuthorities());
        response.sendRedirect(url);
    }
}
